﻿layui.define(['layer', 'toastr', 'pjax', 'xmSelect','treeTable','table'], function (exports) {
    "use strict";
        var $ = layui.jquery,
            layer = layui.layer,
            toastr = layui.toastr,
            pjax = layui.pjax,
            xmSelect = layui.xmSelect,
            table = layui.table,
            treeTable = layui.treeTable;

        var url = '';
         //ajax全局配置 
         $.ajaxSetup({
             beforeSend: function (jqXHR, settings) {
                 //console.log(arguments[1].type);
                 url = arguments[1].url;

                 var now_time = new Date().getTime();
                 var last_time = localStorage.getItem("last_token_time");
                 var expiresMinute = localStorage.getItem("expiresMinute");

                 //需要刷新token 60分钟页面没有任何操作会返回登录页面
                 if ((expiresMinute - ((now_time - last_time) / 60000)) <60) {

                     console.log('时间差：' + (expiresMinute - ((now_time - last_time) / 60000)));

                     var refreshtoken = localStorage.getItem('refresh_token');
                     var time = new Date();
                     var lastTime = localStorage.getItem('lastTime');
                     var span = time.getTime() - lastTime;
                     //console.log(span);
                     if (span > 10000) {

                         var myDate = new Date();
                         localStorage.setItem('lastTime', myDate.getTime());
                         var req = new Request('/api/admin/auth/RefreshToken?refreshtoken=' + refreshtoken, { method: 'GET', cache: 'reload' });
                         fetch(req).then(function (response) {
                             return response.json();

                         }).then(function (res) {
                             if (res.data.accessToken == null || res.data.accessToken == "") {
                           
                                 layer.msg(res.data.msg, {
                                     time: 2000,
                                     end: function () {
                                         os.error('获取身份信息失败，请重新登录！');
                                     }
                                 });
                                 return;
                             }
                             localStorage.setItem("access_token", res.data.accessToken);
                             localStorage.setItem('last_token_time', new Date().getTime());
                         });
                     }

                 }
      
                 var token = localStorage.getItem('access_token');

                 jqXHR.setRequestHeader('Authorization', 'Bearer ' + token)

          
            
           
             },
             //不管是error还是success 都会执行complete
             complete: function (xhr, type) {

                 //console.log(xhr);
                 //console.log(type);
                 if (type === 'timeout') {
                     tool.error('连接超时，请稍后重试！');
                     return;
                 }
                 else if (type === 'error') {
                     // 清除缓存后强制回到登录界面 401表示身份过期
                     if (xhr.status == 401 && xhr.getResponseHeader('Token-Expired') != 'true') {
                         window.location.href = '/admin/login';
                         return;
                     }
                     //这里表示身份过期 token刷新失败
                     else if (xhr.status == 401 && xhr.getResponseHeader('Token-Expired') == 'true') {
                         os.error("身份信息已过期，请联系管理员！");
                         window.location.href = '/admin/login';
                     }

                     if (xhr.status != 404 && xhr.status!=405) {
                         console.log(xhr.status);
                         var code = xhr.responseJSON.code;
                         //这里是权限不足返回403
                         if (code == 403) {
                             os.error("权限不足，请联系管理员！");
                             return;
                         }

                     }

                
                 }
            
             }
        });



        //------消息提示-------------------
        toastr.options = {
            "positionClass": "toast-top-right",
            "timeOut": "500"
        };

    var tmls, tool = {
        error: function (msg) {
            toastr.error(msg);
        },
        warning: function (msg) {
            toastr.warning(msg);
        },
        success: function (msg) {
            toastr.success(msg);
        },

        //xhr---------------------
        xhrSend: function (url,method,parms) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url, true);
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'))
            xhr.responseType = "blob";    // 返回类型blob
            xhr.onload = function () {// 请求完成处理函数
                if (this.status === 200) {
                    var blob = new Blob([this.response], { type: 'application/zip' });// 获取返回值
                    var a = document.createElement('a');
                    a.download = window.decodeURI(xhr.getResponseHeader('Content-Disposition').split(';')[1].split('=')[1], "UTF-8");
                    a.href = window.URL.createObjectURL(blob);
                    a.click();
                }
            }
            xhr.send(JSON.stringify(parms));
        } ,
      
        //下拉多选框------------------------
        selectRender: function (options) {
            var defaults = {
                //filterable: true,//搜索模式
                autoRow: true,//自动换行
                empty: '没有数据!',//空数据提示
                toolbar: { show: true },//工具栏
                theme: {
                    color: '#8dc63f',
                },
                //remoteSearch: true,//远程搜索
                //paging: true,//分页
                //pageSize: 4,//分页大小
                layVerify: 'required',
                layVerType: 'tips',
                direction: 'auto',//下拉方向
                data: [],
                prop: {
                    name: 'name',
                    value: 'id',
                }

            };
            var options = $.extend(defaults, options);
            return xmSelect.render(options);
        },
        
         //下拉单选--------------------------
        selectSingleRender: function (options) {
            var defaults = {
                autoRow: true,//自动换行
                radio: true,//单选
                empty: '没有数据!',//空数据提示
                clickClose: true,
                theme: {
                    color: '#8dc63f',
                },
                model: {
                    icon: 'hidden',
                    label: {
                        type: 'text'
                    }
                },
                layVerify: 'required',
                layVerType: 'tips',
                direction: 'auto',//下拉方向
                data: [],
                prop: {
                    name: 'name',
                    value: 'id',
                }

            };
            var options = $.extend(defaults, options);
            return xmSelect.render(options);
        },




        //treeTable渲染--------------------------
        treeTableRender: function (options) {
            var defaults = {
                loading: false,
                height: 'full-110',
                cellMinWidth: 60,//最小宽度
                page: false,//关闭分页
                method: 'get',//请求方法
                tree: {
                    iconIndex: 1,           // 折叠图标显示在第几列  多选等记得修改
                    isPidData: true,        // 是否是id、pid形式数据
                    idName: 'id',  // id字段名称
                    pidName: 'parentId',     // pid字段名称
                    arrowType: 'arrow2',
                    getIcon: 'ew-tree-icon-style2',
                },
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code == 1 ? 0 : 1,
                        "msg": res.msg,
                        "count": res.count, //解析数据长度
                        "data": res.data //解析数据列表
                    };
                },
            };
            var doneCallback = options.done;
            options.done = function (res, curr, count) {
                //关闭加载
               
                if (doneCallback) {
                    doneCallback(res, curr, count);
                }
            };
            var options = $.extend(defaults, options);
            return treeTable.render(options);
        },


        //treetable重载----------------------------
        treeTableReload: function (tree, options) {
            var defaults = {
                where: {}
            };
            var options = $.extend(defaults, options);
            //options.where.time = new Date().Format("yyyy-MM-dd hh:mm:ss");
            //执行搜索重载
            tree.reload({
                where: options.where
            });
            //关闭加载
            layer.closeAll('loading');
        },


        //layui table----------------------------------
        tableRender: function (options) {
            var defaults = {
                //elem: '#tablelist',//主键
                method: 'get',//请求方法
                limit: 10,//每页数据 默认
                limits: [10, 20, 30, 40, 50],
                //headers: os.getToken(),
                page: true,
                toolbar: true,
                request: {
                    pageName: 'index' //页码的参数名称，默认：page
                    , limitName: 'size' //每页数据量的参数名，默认：limit
                },
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code == 1 ? 0 : 1,
                        "msg": res.msg,
                        "count": res.data.totalCount, //解析数据长度
                        "data": res.data.rows //解析数据列表
                    };
                },
            };
            var options = $.extend(defaults, options);
            return table.render(options);
        },


        //layui table 重载----------------------------
        tableReload: function (tableId, options) {
            var defaults = {
                elem: tableId,//主键 这里是需要刷新的table的id
                page: true,//分页参数
                curr: 1,//当前页
                where: {}
                //headers: os.getToken()
            };
            var options = $.extend(defaults, options);
            //options.where.time = new Date().Format("yyyy-MM-dd hh:mm:ss");
            if (options.page) {

                //执行搜索重载
                table.reload(options.elem, {
                    page: {
                        curr: 1
                    }
                    , where: options.where


                })

            }
            else {
                //执行搜索重载
                table.reload(options.elem, {
                    where: options.where
                });
            }
            ////关闭加载
            layer.closeAll('loading');
        },







        //ajax----------------------------------------
        ajax: function (url, options, callFun, method = 'post') {
            var httpUrl = "/", token = localStorage.getItem('access_token');
            options = method === 'get' ? options : JSON.stringify(options);
            $.ajax(httpUrl + url, {
                data: options,
                contentType: 'application/json;charset=utf-8',
                dataType: 'json', //服务器返回json格式数据
                type: method, //HTTP请求类型
                timeout: 10 * 1000, //超时时间设置为10秒；
                success: function (data, status, xhr) {
                    callFun(data);
                }
                
            });
        },

        //--------layer弹出层----------------------
        Open: function (title, url, width, height, fun) {
            top.layer.open({
                type: 2,
                title: title,
                shadeClose: false,
                shade: 0.2,
                //move:false,
                //btn: ['立即提交', '取消'],
                skin: 'demo-class',
                maxmin: false, //开启最大化最小化按钮
                area: [width, height],
                content: url,
                zIndex: "10000",
                end: function () {
                    if (fun) fun();
                }
            });
        },
        OpenRight: function (title, url, width, height, fun,cancelFun) {
            var index=top.layer.open({
                title: title
                , type: 2
                , area: [width, height]
                , shade: [0.1, '#333']
                , resize: false
                , move: false
                , anim: -1
                , offset: 'rb'
                , zIndex: "1000"
                , shadeClose: false
                , skin: 'layer-anim-07'
                , content: url
                , yes: function () {
                    if (fun) fun();
                }
                , cancel: function (index) {
                    if (cancelFun) cancelFun(index);
                }
            });
            return index;
        },

        //Token--------------------
        getToken: function () {
            var token = localStorage.getItem('access_token');
            return { 'Authorization': 'Bearer ' + token};
        },
        //---关闭所有弹出层
        closeOpen: function () {
            top.layer.closeAll();
        },


        tableLoading: function () {
            tmls = layer.msg('<i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i> 正在加载数据哦', { time: 2000});
        },
        tableLoadingClose: function () {
            setTimeout(function () {
                layer.close(tmls);
            }, 500);
        },
        load: function () {
            $('body').append('<div class="loader-cur-wall"><div class="loader-cur"></div></div>');
        },
        loadClose: function () {
            setTimeout(function () {
                $('.loader-cur-wall').remove();
            }, 100);
        },
        loadRouteNamePath: function (namePath) {
            $("#menuroutePath").text(namePath);
        },
        getUrlParam: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        },
        formatdate: function (str) {
            if (str) {
                var d = eval('new ' + str.substr(1, str.length - 2));
                var ar_date = [
                    d.getFullYear(), d.getMonth() + 1, d.getDate()
                ];
                for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
                return ar_date.slice(0, 3).join('-') + ' ' + ar_date.slice(3).join(':');

                function dFormat(i) { return i < 10 ? "0" + i.toString() : i; }
            } else {
                return "无信息";
            }
        },
        SetSession: function (key, options) {
            localStorage.setItem(key, JSON.stringify(options));
        },
        GetSession: function (key) {
            var obj = localStorage.getItem(key);
            if (obj != null) {
                return JSON.parse(obj);
            }
            return null;
        },
        /**
         * 删除键值对json
         * @param {key} key : 键
         */
        SessionRemove: function (key) {
            localStorage.removeItem(key);
        },
        
        cloudFile: function () {
            $(".fyt-cloud").click(function () {
                var input_text = $(this).data("text");
                var showImg = $(this).data('img');
                var type = $(this).data('type'); //edit=编辑器  sign=默认表单  iframe=弹出层  form=带图片显示
                var frameId = window.frameElement && window.frameElement.id || '',frameUrl='';
                if (frameId) {
                    frameUrl = '&frameid=' + frameId;
                }
                tool.Open('媒体资源库', '/fytadmin/file/cloud/?type=' + type + '&img=' + showImg + '&control=' + input_text + frameUrl, '950px', '600px');
            });
        },
        isExtImage: function(name){
            var imgExt = new Array(".png", ".jpg", ".jpeg", ".bmp", ".gif");
            name = name.toLowerCase();
            var i = name.lastIndexOf(".");
            var ext;
            if (i > -1) {
                ext = name.substring(i);
            }
            for (var i = 0; i < imgExt.length; i++) {
                if (imgExt[i] === ext)
                    return true;
            }
            return false;
        },

        //页面按钮权限-----------------------
        permission: function () {

            var obj = localStorage.getItem('authinfo');
           
             var json= JSON.parse(obj);
            
            //加载权限按钮
            var button = json.buttons;
            //console.log(button);
            $('*[action-code]').each(function (i) {

                //alert($(this).attr('action-code'))
                var code = $(this).attr('action-code');
                var index = $.inArray(code, button);
                if (index < 0) {
                    //没有此按钮权限 隐藏
                    $(this).addClass("layui-hide");
                }
            });

            //加载工具栏权限按钮

            if ($('#tool').html() == null || $('#tool').html() == '') return;
            var tempList = $('#tool').html().toString().split('</a>');
            //console.log(tempList);
            //alert($('#tool').html());
            var returnhtml = '';
            for (var i = 0; i < tempList.length; i++) {
                if (tempList[i].indexOf('<a ') > -1) {

                    if (tempList[i].indexOf('action-code') <= -1) {
                        //无权限控制
                        returnhtml = returnhtml + tempList[i];
                    }
                    else {
                        var html = '';
                        var code = tempList[i].match(/action-code="(\S*)">/)[1].trim();
                        var index = $.inArray(code, button);
                        if (index < 0) {

                            //没有此按钮权限 隐藏
                            var start = tempList[i].indexOf('class="');
                            html = tempList[i].slice(0, start + 7) + " layui-hide " + tempList[i].slice(start + 7)

                        } else {
                            html = tempList[i];
                        }
                        returnhtml = returnhtml + html;
                    }


                }
            }
            $('#tool').html(returnhtml);
        },
        
        chageRoutePath: function (namePath) {
            tool.loadRouteNamePath(namePath);
            localStorage.setItem("routePath", namePath);
        }

 
    };
    exports('common', tool);
});


//日期格式化
Date.prototype.Format = function (fmt) {
    var o = {

        "M+": this.getMonth() + 1, //月份 

        "d+": this.getDate(), //日 

        "h+": this.getHours(), //小时 

        "m+": this.getMinutes(), //分 

        "s+": this.getSeconds(), //秒 

        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 

        "S": this.getMilliseconds() //毫秒 

    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

    for (var k in o)

        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


